<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="所属模块" prop="dataType">
        <el-select v-model="queryParams.dataType" placeholder="请选择所属模块" clearable>
          <el-option v-for="dict in dict.type.cockpit_model" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker v-model="daterangeCreateTime" style="width: 240px" value-format="yyyy-MM-dd" type="daterange"
          range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['input:data:add']">新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['input:data:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['input:data:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['input:data:export']">导出</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="dataList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="id" />
      <el-table-column label="所属模块" align="center" prop="dataType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.cockpit_model" :value="scope.row.dataType" />
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="启用/停用" align="center" prop="status" width="180">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.status" active-value="0" inactive-value="1"
            @change="(value) => handleStatusChange(value, scope.row)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['input:data:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['input:data:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改驾驶舱录入数据对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body class="dialog">
      <el-form :model="form" ref="form" label-width="140px" class="demo-dynamic" :rules="rules">
        <div class="form-item">
          <el-form-item label="所属模块" prop="dataType" :rules="{
            required: true, message: '数据不能为空', trigger: 'blur'
          }">
            <el-select v-model="form.dataType" placeholder="请选择所属模块" :disabled="itemDisable">
              <el-option v-for="dict in dict.type.cockpit_model" :key="dict.value" :label="dict.label"
                :value="dict.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="所属" prop="country" v-if="form.dataType === '1'" :rules="{
            required: true, message: '数据不能为空', trigger: 'blur'
          }">
            <el-select v-model="form.country" placeholder="请选择数据所属" :disabled="itemDisable">
              <el-option v-for="dict in dict.type.cockpit_town_country" :key="dict.value" :label="dict.label"
                :value="dict.value"></el-option>
            </el-select>
          </el-form-item>
        </div>

        <div v-if="form.dataType === '1'">
          <el-divider content-position="left" v-show="form.detailsSex.length !== 0">性别</el-divider>

          <div v-for="(domain, index) in form.detailsSex" :label="'标签名称'" :key="domain.key" class="form-item">
            <el-form-item :label="'标签名称'" :key="'detailsSex.' + index + '.label'"
              :name="'detailsSex.' + index + '.label'" :prop="'detailsSex.' + index + '.label'" :rules="{
                required: true, message: '名称不能为空', trigger: 'blur'
              }">
              <el-input v-model="domain.label"></el-input>
            </el-form-item>
            <el-form-item :label="'标签数据'" :key="'detailsSex.' + index + '.value'"
              :name="'detailsSex.' + index + '.value'" :prop="'detailsSex.' + index + '.value'" :rules="{
                required: true, message: '数据不能为空', trigger: 'blur'
              }">
              <el-input v-model="domain.value"></el-input>
            </el-form-item>
            <div class="form-item-icon">
              <i class="el-icon-remove-outline" @click.prevent="removeFormItem(domain, 'detailsSex')"></i>
              <i class="el-icon-circle-plus-outline" @click.prevent="addFormItem('detailsSex')"
                v-show="index === form.detailsSex.length - 1"></i>
            </div>
          </div>


          <el-divider content-position="left" v-show="form.detailsType.length !== 0">就业类型</el-divider>
          <div v-for="(domain, index) in form.detailsType" :label="'标签名称'" :key="domain.key" class="form-item">
            <el-form-item :label="'标签名称'" :key="'detailsType.' + index + '.label'"
              :name="'detailsType.' + index + '.label'" :prop="'detailsType.' + index + '.label'" :rules="{
                required: true, message: '名称不能为空', trigger: 'blur'
              }">
              <el-input v-model="domain.label"></el-input>
            </el-form-item>
            <el-form-item :label="'标签数据'" :key="'detailsType.' + index + '.value'"
              :name="'detailsType.' + index + '.value'" :prop="'detailsType.' + index + '.value'" :rules="{
                required: true, message: '数据不能为空', trigger: 'blur'
              }">
              <el-input v-model="domain.value"></el-input>
            </el-form-item>
            <div class="form-item-icon">
              <i class="el-icon-remove-outline" @click.prevent="removeFormItem(domain, 'detailsType')"></i>
              <i class="el-icon-circle-plus-outline" @click.prevent="addFormItem('detailsType')"
                v-show="index === form.detailsType.length - 1"></i>
            </div>

          </div>


          <el-divider content-position="left" v-show="form.detailsKill.length !== 0">职业技能</el-divider>
          <div v-for="(domain, index) in form.detailsKill" :label="'标签名称'" :key="domain.key" class="form-item">
            <el-form-item :label="'标签名称'" :key="'detailsKill.' + index + '.label'"
              :name="'detailsKill.' + index + '.label'" :prop="'detailsKill.' + index + '.label'" :rules="{
                required: true, message: '名称不能为空', trigger: 'blur'
              }">
              <el-input v-model="domain.label"></el-input>
            </el-form-item>
            <el-form-item :label="'标签数据'" :key="'detailsKill.' + index + '.value'"
              :name="'detailsKill.' + index + '.value'" :prop="'detailsKill.' + index + '.value'" :rules="{
                required: true, message: '数据不能为空', trigger: 'blur'
              }">
              <el-input v-model="domain.value"></el-input>
            </el-form-item>
            <div class="form-item-icon">
              <i class="el-icon-remove-outline" @click.prevent="removeFormItem(domain, 'detailsKill')"></i>
              <i class="el-icon-circle-plus-outline" @click.prevent="addFormItem('detailsKill')"
                v-show="index === form.detailsKill.length - 1"></i>
            </div>

          </div>

          <el-divider content-position="left" v-show="form.detailsEducation.length !== 0">学历</el-divider>
          <div v-for="(domain, index) in form.detailsEducation" :label="'标签名称'" :key="domain.key" class="form-item">
            <el-form-item :label="'标签名称'" :key="'detailsEducation.' + index + '.label'"
              :name="'detailsEducation.' + index + '.label'" :prop="'detailsEducation.' + index + '.label'" :rules="{
                required: true, message: '名称不能为空', trigger: 'blur'
              }">
              <el-input v-model="domain.label"></el-input>
            </el-form-item>
            <el-form-item :label="'标签数据'" :key="'detailsEducation.' + index + '.value'"
              :name="'detailsEducation.' + index + '.value'" :prop="'detailsEducation.' + index + '.value'" :rules="{
                required: true, message: '数据不能为空', trigger: 'blur'
              }">
              <el-input v-model="domain.value"></el-input>
            </el-form-item>
            <div class="form-item-icon">
              <i class="el-icon-remove-outline" @click.prevent="removeFormItem(domain, 'detailsEducation')"></i>
              <i class="el-icon-circle-plus-outline" @click.prevent="addFormItem('detailsEducation')"
                v-show="index === form.detailsEducation.length - 1"></i>
            </div>

          </div>

          <el-divider content-position="left" v-show="form.detailsAge.length !== 0">年龄</el-divider>

          <div v-for="(domain, index) in form.detailsAge" :label="'标签名称'" :key="domain.key" class="form-item">
            <el-form-item :label="'标签名称'" :key="'detailsAge.' + index + '.label'"
              :name="'detailsAge.' + index + '.label'" :prop="'detailsAge.' + index + '.label'" :rules="{
                required: true, message: '名称不能为空', trigger: 'blur'
              }">
              <el-input v-model="domain.label"></el-input>
            </el-form-item>
            <el-form-item :label="'标签数据'" :key="'detailsAge.' + index + '.value'"
              :name="'detailsAge.' + index + '.value'" :prop="'detailsAge.' + index + '.value'" :rules="{
                required: true, message: '数据不能为空', trigger: 'blur'
              }">
              <el-input v-model="domain.value"></el-input>
            </el-form-item>
            <div class="form-item-icon">
              <i class="el-icon-remove-outline" @click.prevent="removeFormItem(domain, 'detailsAge')"></i>
              <i class="el-icon-circle-plus-outline" @click.prevent="addFormItem('detailsAge')"
                v-show="index === form.detailsAge.length - 1"></i>
            </div>

          </div>

          <el-divider content-position="left" v-show="form.detailsAddress.length === 0">区内区外就业人数</el-divider>
          <div v-for="(domain, index) in form.detailsAddress" :label="'标签名称'" :key="domain.key" class="form-item">
            <el-form-item :label="'标签名称'" :key="'detailsAddress.' + index + '.label'"
              :name="'detailsAddress.' + index + '.label'" :prop="'detailsAddress.' + index + '.label'" :rules="{
                required: true, message: '名称不能为空', trigger: 'blur'
              }">
              <el-input v-model="domain.label"></el-input>
            </el-form-item>
            <el-form-item :label="'标签数据'" :key="'detailsAddress.' + index + '.value'"
              :name="'detailsAddress.' + index + '.value'" :prop="'detailsAddress.' + index + '.value'" :rules="{
                required: true, message: '数据不能为空', trigger: 'blur'
              }">
              <el-input v-model="domain.value"></el-input>
            </el-form-item>
            <div class="form-item-icon">
              <i class="el-icon-remove-outline" @click.prevent="removeFormItem(index, 'detailsAddress')"></i>
              <i class="el-icon-circle-plus-outline" @click.prevent="addFormItem('detailsAddress')"
                v-show="index === form.detailsAddress.length - 1"></i>
            </div>

          </div>

        </div>

        <div v-else>
          <el-divider content-position="left">投诉处理件数</el-divider>

          <div v-for="(domain, index) in form.complaint" :label="'问题类型'" :key="domain.key" class="form-item">
            <el-form-item :label="'问题类型'" :key="'complaint.' + index + '.label'" :name="'complaint.' + index + '.label'"
              :prop="'complaint.' + index + '.label'" :rules="{
                required: true, message: '问题类型不能为空', trigger: 'blur'
              }">
              <el-input v-model="domain.label"></el-input>
            </el-form-item>
            <el-form-item :label="'人数'" :key="'complaint.' + index + '.value'" :name="'complaint.' + index + '.value'"
              :prop="'complaint.' + index + '.value'" :rules="{
                required: true, message: '数据不能为空', trigger: 'blur'
              }">
              <el-input v-model="domain.value"></el-input>
            </el-form-item>
            <div class="form-item-icon">
              <i class="el-icon-remove-outline" @click.prevent="removeFormItem(domain, 'complaint')"></i>
              <i class="el-icon-circle-plus-outline" @click.prevent="addFormItem('complaint')"
                v-show="index === form.complaint.length - 1"></i>
            </div>

          </div>
        </div>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>



  </div>
</template>

<script>
import { addData, close, delData, getData, listData, open, updateData } from "@/api/input/data";
import { getDicts } from "@/api/system/dict/data.js";
const map = {
  detailsSex: 0,
  detailsType: 1,
  detailsKill: 2,
  detailsEducation: 3,
  detailsAge: 4,
  detailsAddress: 5,
}
export default {
  name: "Data",
  dicts: ['sys_normal_disable', 'cockpit_model', 'cockpit_user_attribute', 'cockpit_town_country'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 驾驶舱录入数据表格数据
      dataList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 备注时间范围
      daterangeCreateTime: [],
      // 类型
      attribute: [],
      // 城市类型
      country: [],
      itemDisable: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        // dataType: null,
        status: null,
        createTime: null,
      },
      // 编辑还是新增
      currentId: null,
      // 表单参数
      form: {
        dataType: null,
        remark: null,
        detailsSex: [
          {
            userAttribute: 0,
            label: "",
            value: "",
            townCountry: null
          },
        ],
        detailsType: [
          {
            userAttribute: 0,
            label: "",
            value: "",
            townCountry: null
          },
        ],
        detailsKill: [
          {
            userAttribute: 0,
            label: "",
            value: "",
            townCountry: null
          },
        ],
        detailsEducation: [
          {
            userAttribute: 0,
            label: "",
            value: "",
            townCountry: null
          },
        ],
        detailsAge: [
          {
            userAttribute: 0,
            label: "",
            value: "",
            townCountry: null
          },
        ],
        detailsAddress: [
          {
            userAttribute: 0,
            label: "",
            value: "",
            townCountry: null
          },
        ],
        complaint: [
          {
            userAttribute: 0,
            label: "",
            value: "",
            townCountry: null
          },
        ]
      },
      // 表单校验
      rules: {
        id: [
          { required: true, message: "$comment不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getAttribute();
    this.getCounty();
    console.log('this.form', this.form);

  },
  methods: {

    //
    handleStatusChange(value,row) {
      if(value === '1'){
        // 当前状态为停用  应启用
        close(row.id).then(response => {
          this.$modal.msgSuccess('启用成功');
          this.getList();
        });
      }else{
        open(row.id).then(response => {
          this.$modal.msgSuccess('停用成功');
          this.getList();
        });
        // 当前状态为启用  应停用
      }
    },

    getAttribute() {
      getDicts('cockpit_user_attribute').then((res) => {
        const option = res.data.map((item) => {
          return {
            label: item.dictLabel,
            value: item.dictValue
          }
        })
        console.log('cockpit_user_attribute', option);
        this.initializeForm(option);
        this.attribute = option
      })
    },
    getCounty() {
      getDicts('cockpit_town_country').then((res) => {
        const option = res.data.map((item) => {
          return {
            label: item.dictLabel,
            value: item.dictValue
          }
        })
        console.log('cockpit_town_country', option);
        this.country = option
      })
    },
    /** 查询驾驶舱录入数据列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeCreateTime && '' != this.daterangeCreateTime) {
        this.queryParams.params["beginCreateTime"] = this.daterangeCreateTime[0];
        this.queryParams.params["endCreateTime"] = this.daterangeCreateTime[1];
      }
      listData(this.queryParams).then(response => {
        this.dataList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    removeFormItem(item, value) {
      this.form[value].splice(item, 1);
      console.log('removeFormItem', this.form.detailsAddress.length);

    },
    addFormItem(value) {
      console.log('this.form.details', this.form.details);
      const map = {
        detailsSex: 0,
        detailsType: 1,
        detailsKill: 2,
        detailsEducation: 3,
        detailsAge: 4,
        detailsAddress: 5,
      }
      this.form[value].push({
        userAttribute: map[value],
        label: '',
        value: '',
        townCountry: 1
      })
    },

    initializeForm(options) {
      this.form = {
        dataType: null,
        remark: null,
        detailsSex: [
          {
            userAttribute: 0,
            label: "",
            value: "",
            townCountry: null
          },
        ],
        detailsType: [
          {
            userAttribute: 0,
            label: "",
            value: "",
            townCountry: null
          },
        ],
        detailsKill: [
          {
            userAttribute: 0,
            label: "",
            value: "",
            townCountry: null
          },
        ],
        detailsEducation: [
          {
            userAttribute: 0,
            label: "",
            value: "",
            townCountry: null
          },
        ],
        detailsAge: [
          {
            userAttribute: 0,
            label: "",
            value: "",
            townCountry: null
          },
        ],
        detailsAddress: [
          {
            userAttribute: 0,
            label: "",
            value: "",
            townCountry: null
          },
        ],
        complaint: [
          {
            userAttribute: 0,
            label: "",
            value: "",
            townCountry: null
          },
        ]
      };
      console.log('initializeForm', this.form);

      options.forEach(option => {
        switch (option.value) {
          case "0":
            this.form.detailsSex[0].userAttribute = option.value;
            break;
          case "1":
            this.form.detailsType[0].userAttribute = option.value;
            break;
          case "2":
            this.form.detailsKill[0].userAttribute = option.value;
            break;
          case "3":
            this.form.detailsEducation[0].userAttribute = option.value;
            break;
          case "4":
            this.form.detailsAge[0].userAttribute = option.value;
            break;
          case "5":
            this.form.detailsAddress[0].userAttribute = option.value;
            break;
          default:
            break;
        }
      });

      console.log('initializeForm---', this.form);
    },

    formatData(inputData) {
      const dataType = inputData.dataType;
      const townCountry = inputData.details[0].townCountry;
      // 初始化目标对象
      const formattedData = {
        dataType: dataType,
        country: townCountry,
        remark: inputData.remark,
        detailsSex: [],
        detailsType: [],
        detailsKill: [],
        detailsEducation: [],
        detailsAge: [],
        detailsAddress: [],
        complaint: [],
      };

      // 遍历输入数据的 details 数组
      inputData.details.forEach(item => {
        // 根据 userAttribute 确定字段名称
        const fieldName = Object.keys(map).find(key => map[key] === parseInt(item.userAttribute));

        // 如果找到了对应的字段名称，则将数据添加到相应的数组中
        if (dataType === '1') {
          formattedData[fieldName].push({
            userAttribute: parseInt(item.userAttribute),
            label: item.label,
            value: item.value,
            townCountry: item.townCountry,
          });
        } else {
          // 如果没有找到对应的字段名称，可以将其添加到 complaint 数组中
          formattedData.complaint.push({
            userAttribute: parseInt(item.userAttribute),
            label: item.label,
            value: item.value,
            townCountry: item.townCountry,
          });
        }
      });

      return formattedData;
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      // this.form = this.form;
      this.itemDisable = false;
      this.initializeForm(this.attribute);
      // this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeCreateTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据          
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.currentId = 0;
      this.title = "添加驾驶舱录入数据";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      // this.reset();
      const id = row.id || this.ids
      getData(id).then(response => {
        const data = this.formatData(response.data);
        console.log('data',response.data);
        this.currentId = response.data.id;
        this.form = data;
        this.open = true;
        this.itemDisable = true;
        this.title = "修改驾驶舱录入数据";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        console.log('this.form', this.form);
        const { dataType } = this.form;
        let data = {};
        if (dataType === '2') {
          const details = this.form.complaint;
          details.map((item) => {
            return {
              ...item,
              townCountry: this.form.townCountry
            }
          })
          data = {
            dataType: '2',
            details: details,
            id: this.currentId,
          }
        } else {
          const details = [
            ...this.form.detailsSex,
            ...this.form.detailsType,
            ...this.form.detailsKill,
            ...this.form.detailsEducation,
            ...this.form.detailsAge,
            ...this.form.detailsAddress,
          ]
          details.map((item) => {
            return {
              ...item,
              townCountry: this.form.townCountry
            }
          })
          data = {
            dataType: '1',
            details: details,
            id: this.currentId,
          }
        }

        if (valid) {
          if (this.currentId) { // 为true  编辑  更新
            updateData(data).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.itemDisable = false;
              this.getList();
            });
          } else { // false 新增
            addData(data).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除驾驶舱录入数据编号为"' + ids + '"的数据项？').then(function () {
        return delData(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('input/data/export', {
        ...this.queryParams
      }, `data_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style lang="less" scoped>
.form-item {
  display: flex;
  align-items: center;

  .el-form-item {
    // margin: 5px 0;
  }
}

i {
  font-size: 20px;
  margin: 0 0 20px 0;
}

.dialog {
  ::v-deep.el-dialog {
    .el-dialog__body {
      height: 700px;
      overflow: auto;
    }
  }
}
</style>
